<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>钉钉机器人管理</title>
  <style>
    body{font-size:18px;margin:40px;font-family:Arial,Helvetica,sans-serif}
    input{width:360px;padding:4px;font-size:16px}
    button{padding:6px 12px;font-size:16px;margin-left:6px}
    table{margin-top:20px;font-size:17px;border-collapse:collapse;width:100%}
    th,td{border:1px solid #ccc;padding:8px 10px}
    .nav{margin-bottom:20px}.nav a{margin-right:15px;font-weight:bold}
  </style>
</head>
<body>
<div class="nav">
  <a href="index.html">首页</a>
  <a href="schedule.html">报警设置</a>
  <a href="log.html">报警日志</a>
  <button class="bigscreen-btn" onclick="location.href='bigscreen.html'">📺 大屏</button>
</div>

<h2>钉钉机器人管理</h2>

<div>
  <input id="name" placeholder="名称（如：运维群机器人）">
  <input id="token" placeholder="AccessToken">
  <input id="secret" placeholder="加签Secret">
  <button onclick="saveRobot()">保存</button>
</div>

<table id="list">
  <thead><tr><th>名称</th><th>Token</th><th>Secret</th><th>操作</th></tr></thead>
  <tbody></tbody>
</table>

<script>
const BASE = window.location.origin;

async function api(url, obj) {
  const r = await fetch(BASE + url, {
    method: obj ? 'POST' : 'GET',
    headers: obj ? {'Content-Type':'application/json'} : {},
    body: obj ? JSON.stringify(obj) : undefined
  });
  return r.json();
}
async function loadRobots() {
  const arr = await api('/api/ding');
  const tb = document.querySelector('#list tbody');
  tb.innerHTML = '';
  arr.forEach(r=>{
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${r.name}</td>
      <td>${r.token.slice(0,12)}...</td>
      <td>${r.secret.slice(0,12)}...</td>
      <td><button onclick="delRobot(${r.id})">删除</button></td>`;
    tb.appendChild(tr);
  });
}
async function saveRobot() {
  const name = document.getElementById('name').value.trim();
  const token = document.getElementById('token').value.trim();
  const secret = document.getElementById('secret').value.trim();
  if(!name||!token||!secret) return alert('三项均不能为空！');
  await api('/api/ding', {id:0, name, token, secret});
  loadRobots();
  // 清空输入框
  ['name','token','secret'].forEach(id=>document.getElementById(id).value='');
}
async function delRobot(id) {
  if(!confirm('确定删除？')) return;
  await fetch(BASE + '/api/ding/' + id, {method:'DELETE'});
  loadRobots();
}
loadRobots();
</script>
</body>
</html>